package com.yonyou.cyxdms.sysAuth.service.service.manage.company;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yonyou.cyxdms.sysAuth.service.constants.CommonConstants;
import com.yonyou.cyxdms.sysAuth.service.dto.FileUploadInfoDTO;

import com.yonyou.cyx.framework.bean.dto.framework.RestResultResponse;
import com.yonyou.cyx.framework.service.excel.ExcelDataType;
import com.yonyou.cyx.framework.service.excel.ExcelExportColumn;
import com.yonyou.cyx.framework.service.excel.ExcelGenerator;
import com.yonyou.cyx.framework.util.bean.ApplicationContextHelper;
import com.yonyou.cyx.function.exception.ServiceBizException;
import com.yonyou.cyx.function.utils.bean.BeanMapperUtil;
import com.yonyou.cyx.function.utils.common.StringUtils;
import com.yonyou.cyxdms.basedata.client.domains.vo.RegionVO;
import com.yonyou.cyxdms.basedata.client.service.basedata.BaseCommonRegionService;
import com.yonyou.cyxdms.framework.bean.dto.user_info.LoginInfoDto;
import com.yonyou.cyxdms.sysAuth.service.constants.ManageDictCodeConstants;
import com.yonyou.cyxdms.sysAuth.service.dto.CompanyDTO;
import com.yonyou.cyxdms.sysAuth.service.dto.EquityDto;
import com.yonyou.cyxdms.sysAuth.service.entity.CompanyPO;
import com.yonyou.cyxdms.sysAuth.service.entity.EquityPo;
import com.yonyou.cyxdms.sysAuth.service.entity.FileUploadInfoPO;
import com.yonyou.cyxdms.sysAuth.service.entity.OrgPO;
import com.yonyou.cyxdms.sysAuth.service.feign.channelclient.CmsIsChannelClient;
import com.yonyou.cyxdms.sysAuth.service.mapper.CompanyMapper;
import com.yonyou.cyxdms.sysAuth.service.mapper.EquityStructureMapper;
import com.yonyou.cyxdms.sysAuth.service.mapper.FileUploadInfoMapper;
import com.yonyou.cyxdms.sysAuth.service.service.impl.EquityStructureService;
import com.yonyou.cyxdms.sysAuth.service.service.org.OrgService;
import com.yonyou.cyxdms.sysmanage.client.feign.CmsChannelClient;
import io.rong.exception.Error;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.logging.log4j.util.StringMap;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, CompanyPO> implements CompanyService {

    @Value("${store.default.pic.name}")
    private String STORE_DEFAULT_PIC_NAME;
    @Value("${store.default.pic.url}")
    private String STORE_DEFAULT_PIC_URL;



    @Resource
    CompanyMapper companyMapper;

    @Resource
    private ExcelGenerator excelService;

    @Autowired
    FileUploadInfoService fileUploadInfoService;

    @Resource
    private EquityStructureMapper equityStructureMapper;


    @Autowired
    FileUploadInfoMapper fileUploadInfoMapper;

    @Autowired
    private CmsChannelClient cmsChannelClient;
    @Autowired
    private CmsIsChannelClient cmsIsChannelClient;
    @Autowired
    OrgService orgService;

    @Autowired
    private BaseCommonRegionService baseCommonRegionService;

    private final Logger logger = LoggerFactory.getLogger(CompanyServiceImpl.class);


    @Override
    @SuppressWarnings("unchecked")
    @Transactional(readOnly = true)
    public IPage<Map<String, Object>> selectPageBysql(Page page, Map<String, Object> queryCondition) {
        // 获取总条数
        page.setRecords(companyMapper.selectPageBySql(page, queryCondition));
        return page;
    }

    @Override
    @Transactional
    public Map<String, Object> insert(CompanyDTO companyDTO) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        String appId = loginInfoDto.getAppId();

        companyDTO.setCompanyCode(generateCompanyCode());
        //校验company_code
        CompanyPO companypo4Check = companyMapper.selectOne(new LambdaQueryWrapper<CompanyPO>()
                .eq(CompanyPO::getAppId, appId)
                .eq(CompanyPO::getCompanyCode, companyDTO.getCompanyCode()));
        if(companypo4Check != null){
            throw new ServiceBizException("公司代码【"+companyDTO.getCompanyCode()+"】已存在");
        }

        CompanyPO factorycompanypo = companyMapper.selectOne(new LambdaQueryWrapper<CompanyPO>()
            .eq(CompanyPO::getAppId, appId)
            .eq(CompanyPO::getCompanyType, ManageDictCodeConstants.ORG_TYPE_FACTORY));

        CompanyPO companypo = new CompanyPO();
        BeanUtils.copyProperties(companyDTO, companypo);
        companypo.setAppId(appId);
        companypo.setOrgId(Integer.MAX_VALUE);
        companypo.setCompanyType(ManageDictCodeConstants.ORG_TYPE_DEALER_COMPANY);
        companypo.setDataType(ManageDictCodeConstants.DATA_TYPE_BY_OWNER);
        companypo.setFactoryCompanyId(factorycompanypo.getCompanyId());
        transRegion(companypo, companyDTO, appId);

        String createdBy = "-1";
        LocalDateTime createdAt = LocalDateTime.now();
        if(loginInfoDto != null && loginInfoDto.getUserId() != null){
            createdBy = loginInfoDto.getUserId().toString();
        }
        companypo.setCreatedBy(createdBy);
        companypo.setUpdatedBy(createdBy);
        companypo.setCreatedAt(createdAt);
        companypo.setUpdatedAt(createdAt);

        companyMapper.insert(companypo);
        //step1股权结构信息
        List<EquityDto> insertEquityList = companyDTO.getInsertEquityList();
        if(CollectionUtils.isNotEmpty(insertEquityList)){
            saveEquityInfo(companypo.getCompanyId(),insertEquityList,companypo.getCompanyCode());
        }
        //step2 保存附件
        this.insertCompanyUrl(companyDTO, companypo.getCompanyId().longValue());
        if(CollectionUtils.isNotEmpty(companyDTO.getStorePics())){
            this.insertStorePic(companyDTO, companypo.getCompanyId().longValue());
        }
        //保存组织，并更新组织id
        Long orgId = saveOrg(companypo);
        companypo.setOrgId(orgId.intValue());
        companyMapper.updateById(companypo);
        return companypo.toMaps();
    }
    //step2 保存附件
    private void insertCompanyUrl(CompanyDTO companyDTO, Long companyId) {
        fileUploadInfoService.insertFiles(companyId, ManageDictCodeConstants.COMPANY_FILE, companyDTO.getCaseUrl());
    }

    private void insertStorePic(CompanyDTO companyDTO, Long companyId) {
        fileUploadInfoService.insertFiles(companyId, ManageDictCodeConstants.COMPANY_STORE_PIC, companyDTO.getStorePics());
    }
    /**
     * 保存股权信息
     *
     * @return
     */
    private Integer saveEquityInfo(Integer companyId,List<EquityDto> insertEquityList,String companyCode) {
        if(CollectionUtils.isEmpty(insertEquityList)){
            return 0;
        }
        String createdBy = "-1";
        LocalDateTime createdAt = LocalDateTime.now();
        insertEquityList.forEach(dto -> {
            EquityPo po = new EquityPo();
            po.setCompanyId(companyId);
            po.setCompanyCode(companyCode);
            po.setShareholderName(dto.getShareholderName());
            po.setEquityRatio(dto.getEquityRatio());
            po.setInputAmount(dto.getInputAmount());
            po.setCreatedBy(createdBy);
            po.setCreatedAt(createdAt);
            po.setUpdatedBy(createdBy);
            po.setUpdatedAt(createdAt);
            po.setIsDeleted(ManageDictCodeConstants.STATUS_IS_NOT);
            equityStructureMapper.insert(po);
        });
        return insertEquityList.size();
    }

    /**
     * 获取公司代码
     * 范围 100001 ~ 999999
     * @return
     */
    private synchronized String generateCompanyCode(){
        Integer low = 100001;
        Integer high = 999999;
        Integer companyCode = 0;
        LambdaQueryWrapper<CompanyPO> qw = new LambdaQueryWrapper<CompanyPO>().select(CompanyPO::getCompanyCode)
                .between(CompanyPO::getCompanyCode, low, high)
                .orderByDesc(CompanyPO::getCompanyCode);
        List<CompanyPO> companyList = companyMapper.selectList(qw);
        if(CollectionUtils.isEmpty(companyList)){
            companyCode = low;
        }else{
            companyCode = new Integer(companyList.get(0).getCompanyCode()) + 1;
        }
        return String.valueOf(companyCode);
    }

    private Long saveOrg(CompanyPO companypo){
        OrgPO orgpo = new OrgPO();
        orgpo.setCompanyId(companypo.getCompanyId().longValue());
        orgpo.setAppId(companypo.getAppId());
        orgpo.setOrgCode(companypo.getCompanyCode());
        orgpo.setOrgName(companypo.getCompanyNameCn());
        orgpo.setOrgShortName(companypo.getCompanyShortNameCn());
        orgpo.setOrgType(ManageDictCodeConstants.ORG_TYPE_DEALER_COMPANY);
        orgpo.setDataType(ManageDictCodeConstants.DATA_TYPE_BY_OWNER);
        orgpo.setIsValid(ManageDictCodeConstants.STATUS_IS_VALID);
        orgpo.setOrgId(Long.MAX_VALUE);
        orgService.addOrg(orgpo);
        return orgpo.getOrgId();
    }

    private void transRegion(CompanyPO companypo, CompanyDTO companyDTO, String appId){

        if(companyDTO.getProvinceId() != null){
            RestResultResponse<RegionVO> provinceResult = cmsIsChannelClient.getRegionById(companyDTO.getProvinceId());
            if(!provinceResult.isSuccess() || provinceResult.getData() == null){
                throw new ServiceBizException("获取省份数据失败");
            }
            RegionVO provinceVo = provinceResult.getData();
            companypo.setProvinceCode(provinceVo.getRegionCode());
            companypo.setProvinceName(provinceVo.getRegionName());
        }

        if(companyDTO.getCityId() != null){
            RestResultResponse<RegionVO> cityResult = cmsIsChannelClient.getRegionById(companyDTO.getCityId());
            if(!cityResult.isSuccess() || cityResult.getData() == null){
                throw new ServiceBizException("获取城市数据失败");
            }
            RegionVO cityVo = cityResult.getData();
            companypo.setCityCode(cityVo.getRegionCode());
            companypo.setCityName(cityVo.getRegionName());
        }

        if(companyDTO.getDistrictId() != null){
            RestResultResponse<RegionVO> districtResult = cmsIsChannelClient.getRegionById(companyDTO.getDistrictId());
            if(!districtResult.isSuccess() || districtResult.getData() == null){
                throw new ServiceBizException("获取区县数据失败");
            }
            RegionVO districtVo = districtResult.getData();
            companypo.setDistrictCode(districtVo.getRegionCode());
            companypo.setDistrictName(districtVo.getRegionName());
        }

    }
    /**
     * 修改公司信息
     *
     * @return
     */
    @Override
    @Transactional
    public Map<String, Object> update(Integer companyId,CompanyDTO companyDTO) {
        CompanyPO companypo = companyMapper.selectById(companyId);
        String appId = companypo.getAppId();
        BeanUtils.copyProperties(companyDTO, companypo);
        transRegion(companypo, companyDTO, appId);

        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        String updatedBy = "-1";
        LocalDateTime updatedAt = LocalDateTime.now();
        if(loginInfoDto != null && loginInfoDto.getUserId() != null){
            updatedBy = loginInfoDto.getUserId().toString();
        }
        companypo.setUpdatedBy(updatedBy);
        companypo.setUpdatedAt(updatedAt);
        companypo.setCompanyId(companyId);
        companypo.setUpdatedBy(LocalDateTime.now().toString());
        companyMapper.updateById(companypo);
        //step1 股权结构修改信息
        List<EquityDto> updateEquityList = equityStructureMapper.selectByCompanyId(companyId);
        updateEquityList.forEach(list->{
            if (companyId.equals(list.getCompanyId())){
                equityStructureMapper.deleteById(list.getEquityId());
        }
        });
        saveEquityInfo(companypo.getCompanyId(),companyDTO.getInsertEquityList(),companypo.getCompanyCode());
        //step2 修改附件

        Integer billType = 17291001 ;
        List<FileUploadInfoDTO> fileUploadInfoList = fileUploadInfoService.selectFileByCompanyId(companyId, billType);
        fileUploadInfoList.forEach(list -> {
            if (companyId.equals(list.getBillId())){
                fileUploadInfoService.deleteById(list.getFileUploadInfoId().longValue());
            }
        });
        if (CollectionUtils.isNotEmpty(companyDTO.getCaseUrl())){
            this.insertCompanyUrl(companyDTO, companypo.getCompanyId().longValue());
        }

        List<FileUploadInfoDTO> storePicList = fileUploadInfoService.selectFileByCompanyId(companyId, ManageDictCodeConstants.COMPANY_STORE_PIC);
        storePicList.forEach(t -> {
            fileUploadInfoService.deleteById(t.getFileUploadInfoId().longValue());
        });
        if(CollectionUtils.isNotEmpty(companyDTO.getStorePics())){
            this.insertStorePic(companyDTO, companypo.getCompanyId().longValue());
        }else{
            Map<String, String> defaultPic = new HashMap<>();
            defaultPic.put("url", STORE_DEFAULT_PIC_URL);
            defaultPic.put("name", STORE_DEFAULT_PIC_NAME);
            List<Map<String, String>> storePics = new ArrayList<>();
            storePics.add(defaultPic);
            companyDTO.setStorePics(storePics);
            this.insertStorePic(companyDTO, companypo.getCompanyId().longValue());
        }
        return companypo.toMaps();
    }


    @Override
    public CompanyDTO detail(Integer companyId) {
        CompanyPO companypo = companyMapper.selectById(companyId);
        List<EquityDto> equityList = equityStructureMapper.selectByCompanyId(companyId);
        CompanyDTO companyDTO = new CompanyDTO();
        BeanUtils.copyProperties(companypo, companyDTO);
        if (CollectionUtils.isNotEmpty(equityList)){
            //step2 获取股权信息.
            companyDTO.setInsertEquityList(equityList);
        }
        //step2 获取附件信息
        companyDTO.setCaseUrl(this.getNotificationUrl(companyId.longValue()));
        //门头图片
        companyDTO.setStorePics(this.getStorePic(companyId.longValue()));
        return companyDTO;
    }

    @Override
    public List<CompanyDTO> getListByParam(Map<String,Object> params){
        List<CompanyPO> companypos = companyMapper.selectByMap(params);
        List<CompanyDTO> list = new ArrayList<>();
        if(CollectionUtils.isEmpty(companypos)){
            return list;
        }else{
            companypos.forEach(po -> {
                CompanyDTO dto = new CompanyDTO();
                BeanUtils.copyProperties(po, dto);
                //step1 获取附件信息
                dto.setCaseUrl(this.getNotificationUrl(dto.getCompanyId().longValue()));
                list.add(dto);
            });
        }
        return list;
    }
    //step1 获取附件信息
    private List<Map<String, String>> getNotificationUrl(Long companyId) {
        List<FileUploadInfoPO> fileUploadInfoPos = fileUploadInfoMapper.selectList(new LambdaQueryWrapper<FileUploadInfoPO>()
                .eq(FileUploadInfoPO::getBillId, companyId)
                .eq(FileUploadInfoPO::getBillType, ManageDictCodeConstants.COMPANY_FILE));
        List<Map<String, String>> caseUrl = new ArrayList<>();
        for(FileUploadInfoPO po : fileUploadInfoPos){
            Map<String, String> url = new HashMap<>();
            url.put("url", po.getFileId());
            url.put("name", po.getFileName());
            caseUrl.add(url);
        }
        return caseUrl;
    }

    private List<Map<String,String>> getStorePic(Long companyId){
        List<FileUploadInfoPO> storePicList = fileUploadInfoMapper.selectList(new LambdaQueryWrapper<FileUploadInfoPO>()
                .eq(FileUploadInfoPO::getBillId, companyId)
                .eq(FileUploadInfoPO::getBillType, ManageDictCodeConstants.COMPANY_STORE_PIC));
        List<Map<String, String>> storePics = new ArrayList<>();
        for(FileUploadInfoPO po : storePicList){
            Map<String, String> url = new HashMap<>();
            url.put("url", po.getFileId());
            url.put("name", po.getFileName());
            storePics.add(url);
        }
        return storePics;
    }
    @Override
    public void getListForExport(CompanyDTO companyDTO, HttpServletRequest request, HttpServletResponse response) {
        List<CompanyDTO> comInfoListByPage = companyMapper.getComInfoListByPage(companyDTO);
        List<Map> list = toListMap(comInfoListByPage);
        List<Map> exportMaps = new ArrayList<>();
        Map<String, List<Map>> excelData = new HashMap<>(16);
        comInfoListByPage.forEach(companyList ->{
            exportMaps.add(BeanMapperUtil.toMap(companyList));
        });
        excelData.put("公司信息维护表", list);
        List<ExcelExportColumn> exportCompanyList = new ArrayList<>();
        exportCompanyList.add(new ExcelExportColumn("companyCode", "公司代码"));
        exportCompanyList.add(new ExcelExportColumn("companyNameCn", "公司名称"));
        exportCompanyList.add(new ExcelExportColumn("companyShortNameCn", "公司简称"));
        exportCompanyList.add(new ExcelExportColumn("companyNameEn", "公司名称(英文)"));
        exportCompanyList.add(new ExcelExportColumn("provinceName", "省份"));
        exportCompanyList.add(new ExcelExportColumn("cityName", "城市"));
        exportCompanyList.add(new ExcelExportColumn("districtName", "区县"));
        exportCompanyList.add(new ExcelExportColumn("addressCn", "公司地址"));
        exportCompanyList.add(new ExcelExportColumn("representative", "法人"));
        exportCompanyList.add(new ExcelExportColumn("representativeTel", "法人联系方式"));
        exportCompanyList.add(new ExcelExportColumn("representativeEmail", "法人邮箱"));
        exportCompanyList.add(new ExcelExportColumn("registeredCapital", "注册资金(万元)"));
        exportCompanyList.add(new ExcelExportColumn("unifiedSocialCreditCode", "统一社会信用代码"));
        exportCompanyList.add(new ExcelExportColumn("establishmentDate", "成立时间"));
        exportCompanyList.add(new ExcelExportColumn("registerAddress", "注册地址"));
        exportCompanyList.add(new ExcelExportColumn("zipCode", "邮编"));
        exportCompanyList.add(new ExcelExportColumn("eMail", "公司E-MAIL"));
        exportCompanyList.add(new ExcelExportColumn("validStatus", "有效状态", ExcelDataType.Dict));
        excelService.generateExcel(excelData, exportCompanyList, "公司信息维护表.xlsx", request, response);
    }


    public List<Map> toListMap(List<CompanyDTO> companylist) {
        List<Map> result = new ArrayList<>();
        for (CompanyDTO dto : companylist) {
            Map map = JSONObject.parseObject(JSONObject.toJSONString(dto), new TypeReference<Map>() {
            });
            result.add(map);
        }
        return result;
    }

    @Override
    @Transactional
    public Map<String, String> getMainDataSync(List<Map> companyMap) {
        HashMap<String, String> result = new HashMap<>();
        companyMap.forEach(map -> {
            CompanyPO companyPo = new CompanyPO();
            String companyCode = (String) map.get("KUNNR");

            if (StringUtils.isNullOrEmpty(companyCode)) {
                result.put("IS_RESULT", "N");
                result.put("IS_MESSAGE", "失败");
                throw new IllegalArgumentException("公司代码不能为空");
            }
            logger.info("companyCode:{}",companyCode);
            String replaceFirst = companyCode.replaceFirst("^0*", "");
            String dealerType = map.get("KUKLA").toString();
            Integer intDealerType1 = this.selectDealerType(dealerType);
            companyPo.setDealerType(intDealerType1);
            companyPo.setCompanyShortNameCn((String) map.get("BU_SORT1_TXT"));
            companyPo.setCompanyNameCn((String) map.get("NAME1"));
            companyPo.setRegisterAddress((String) map.get("STRAS"));
            companyPo.setZipCode((String) map.get("PSTLZ"));
            companyPo.setUnifiedSocialCreditCode((String) map.get("TAXNUMXL"));
            companyPo.setAppId(ManageDictCodeConstants.APP_ID);
            companyPo.setCompanyType(ManageDictCodeConstants.ORG_TYPE_DEALER_COMPANY);
            companyPo.setValidStatus(ManageDictCodeConstants.STATUS_IS_VALID);
            companyPo.setFactoryCompanyId(1);
            companyPo.setDataType(ManageDictCodeConstants.DATA_TYPE_BY_OWNER);
            companyPo.setUpdatedAt(LocalDateTime.now());
            companyPo.setCompanyCode(replaceFirst);
            companyPo.setOrgId(0);
            //添加公司信息
            if (!StringUtils.isNullOrEmpty(map.get("REGIO"))) {
                RestResultResponse<Map<String, String>> restResultResponse = this.cmsChannelClient.getProvinceByNameLike((String) map.get("REGIO"));
                if (!StringUtils.isNullOrEmpty(restResultResponse)) {
                    Map<String, String> data = restResultResponse.getData();
                    String regionCode = data.get("regionCode");
                    Integer regionId = Integer.valueOf(data.get("regionId"));
                    companyPo.setProvinceCode(regionCode);
                    companyPo.setProvinceId(Integer.valueOf(regionId));
                    companyPo.setProvinceName((String) map.get("REGIO"));
                    if (!StringUtils.isNullOrEmpty(map.get("ORT01"))) {
                        RestResultResponse<Map<String, String>> cityRestResultResponse = this.cmsChannelClient.getCityByNameLike((String) map.get("ORT01"), Long.valueOf(regionId));
                        Map<String, String> cityDataMap = cityRestResultResponse.getData();
                        companyPo.setCityName((String) map.get("ORT01"));
                        if (!StringUtils.isNullOrEmpty(cityDataMap)) {
                            companyPo.setCityId(Integer.valueOf(cityDataMap.get("regionId")));
                            companyPo.setCityCode(cityDataMap.get("regionCode"));
                        }
                    }
                }
            } else {
                if (!StringUtils.isNullOrEmpty((String) map.get("ORT01"))) {
                    RestResultResponse<Map<String, String>> resultMap = this.cmsChannelClient.getProvinceByCityName((String) map.get("ORT01"));
                    Map<String, String> resultMapData = resultMap.getData();
                    if (!StringUtils.isNullOrEmpty(resultMapData)) {
                        String regionId = resultMapData.get("regionId");
                        companyPo.setProvinceName(resultMapData.get("regionName"));
                        companyPo.setProvinceCode(resultMapData.get("regionCode"));
                        companyPo.setProvinceId(Integer.valueOf(regionId));
                        RestResultResponse<Map<String, String>> cityRestResultResponse = this.cmsChannelClient.getCityByNameLike((String) map.get("ORT01"), Long.valueOf(regionId));
                        Map<String, String> cityDataMap = cityRestResultResponse.getData();
                        companyPo.setCityName((String) map.get("ORT01"));
                        if (!StringUtils.isNullOrEmpty(cityDataMap)) {
                            companyPo.setCityId(Integer.valueOf(cityDataMap.get("regionId")));
                            companyPo.setCityCode(cityDataMap.get("regionCode"));
                        }
                    }
                }
            }
            QueryWrapper<CompanyPO> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("COMPANY_CODE", replaceFirst);
            CompanyPO queryCompanyPo = this.companyMapper.selectOne(queryWrapper);
            result.put("IS_RESULT", "Y");
            result.put("IS_MESSAGE", "成功");
            if (StringUtils.isNullOrEmpty(queryCompanyPo)) {
                companyPo.setCreatedAt(LocalDateTime.now());
                logger.info("客户主数据同步执行新增------------------:{}",companyPo);
                this.companyMapper.insert(companyPo);
            } else {
                if (!StringUtils.isNullOrEmpty(map.get("REGIO"))) {
                    RestResultResponse<Map<String, String>> restResultResponse = this.cmsChannelClient.getProvinceByNameLike((String) map.get("REGIO"));
                    Map<String, String> data = restResultResponse.getData();
                    if (!StringUtils.isNullOrEmpty(data)) {
                        String regionCode = data.get("regionCode");
                        Integer regionId = Integer.valueOf(data.get("regionId"));
                        queryCompanyPo.setProvinceCode(regionCode);
                        queryCompanyPo.setProvinceId(Integer.valueOf(regionId));
                        RestResultResponse<Map<String, String>> cityRestResultResponse = this.cmsChannelClient.getCityByNameLike((String) map.get("ORT01"), Long.valueOf(regionId));
                        Map<String, String> cityDataMap = cityRestResultResponse.getData();
                        if (!StringUtils.isNullOrEmpty(cityDataMap)) {
                            queryCompanyPo.setCityId(Integer.valueOf(cityDataMap.get("regionId")));
                            queryCompanyPo.setCityCode(cityDataMap.get("regionCode"));
                        }
                    }
                } else {
                    RestResultResponse<Map<String, String>> resultMap = this.cmsChannelClient.getProvinceByCityName((String) map.get("ORT01"));
                    Map<String, String> resultMapData = resultMap.getData();
                    if (!StringUtils.isNullOrEmpty(resultMapData)) {
                        String regionId = resultMapData.get("regionId");
                        queryCompanyPo.setProvinceName(resultMapData.get("regionName"));
                        queryCompanyPo.setProvinceCode(resultMapData.get("regionCode"));
                        RestResultResponse<Map<String, String>> cityRestResultResponse = this.cmsChannelClient.getCityByNameLike((String) map.get("ORT01"), Long.valueOf(regionId));
                        Map<String, String> cityDataMap = cityRestResultResponse.getData();
                        if (!StringUtils.isNullOrEmpty(cityDataMap)) {
                            queryCompanyPo.setCityId(Integer.valueOf(cityDataMap.get("regionId")));
                            queryCompanyPo.setCityCode(cityDataMap.get("regionCode"));
                        }
                    }
                }
                RestResultResponse<Map<String, String>> resultMap = this.cmsChannelClient.getProvinceByCityName((String) map.get("ORT01"));
                Map<String, String> resultMapData = resultMap.getData();
                if (!StringUtils.isNullOrEmpty(resultMapData)) {
                    String regionId = resultMapData.get("regionId");
                    queryCompanyPo.setProvinceName(resultMapData.get("regionName"));
                    queryCompanyPo.setProvinceCode(resultMapData.get("regionCode"));
                    RestResultResponse<Map<String, String>> cityRestResultResponse = this.cmsChannelClient.getCityByNameLike((String) map.get("ORT01"), Long.valueOf(regionId));
                    Map<String, String> cityDataMap = cityRestResultResponse.getData();
                    if (!StringUtils.isNullOrEmpty(cityDataMap)) {
                        queryCompanyPo.setCityId(Integer.valueOf(cityDataMap.get("regionId")));
                        queryCompanyPo.setCityCode(cityDataMap.get("regionCode"));
                    }

                    //companyDTO.setClient(companyMap.get("KUKLA"));
                    //添加公司信息
                    if (!StringUtils.isNullOrEmpty(resultMapData)) {
                        String regionCode = resultMapData.get("regionCode");
                        Integer regionId2 = Integer.valueOf(resultMapData.get("regionId"));
                        companyPo.setProvinceCode(regionCode);
                        companyPo.setProvinceId(Integer.valueOf(regionId));
                        RestResultResponse<Map<String, String>> cityRestResultResponse2 = this.cmsChannelClient.getCityByNameLike((String) map.get("ORT01"), Long.valueOf(regionId));
                        Map<String, String> cityDataMap2 = cityRestResultResponse.getData();
                        if (!StringUtils.isNullOrEmpty(cityDataMap)) {
                            queryCompanyPo.setCityId(Integer.valueOf(cityDataMap.get("regionId")));
                            queryCompanyPo.setCityCode(cityDataMap.get("regionCode"));
                            queryCompanyPo.setCompanyCode(replaceFirst);
                        }
                    }


                }
                queryCompanyPo.setCompanyShortNameCn((String) map.get("BU_SORT1_TXT"));
                queryCompanyPo.setCompanyNameCn((String) map.get("NAME1"));
                queryCompanyPo.setRegisterAddress((String) map.get("STRAS"));
                queryCompanyPo.setProvinceName((String) map.get("REGIO"));
                queryCompanyPo.setCityName((String) map.get("ORT01"));
                queryCompanyPo.setZipCode((String) map.get("PSTLZ"));
                queryCompanyPo.setUnifiedSocialCreditCode((String) map.get("TAXNUMXL"));
                queryCompanyPo.setAppId(ManageDictCodeConstants.APP_ID);
                queryCompanyPo.setCompanyType(ManageDictCodeConstants.ORG_TYPE_DEALER_COMPANY);
                queryCompanyPo.setFactoryCompanyId(1);
                queryCompanyPo.setValidStatus(ManageDictCodeConstants.STATUS_IS_VALID);
                queryCompanyPo.setDataType(ManageDictCodeConstants.DATA_TYPE_BY_OWNER);
                Integer intDealerType = this.selectDealerType(dealerType);
                queryCompanyPo.setDealerType(intDealerType);
                queryCompanyPo.setOrgId(0);
                //3.跟新
                queryCompanyPo.setUpdatedAt(LocalDateTime.now());
                logger.info("客户主数据同步执行修改------------------{}",queryCompanyPo);
                this.companyMapper.updateById(queryCompanyPo);
            }
        });
        return result;
    }
//查询公司代码
    @Override
    public  CompanyDTO selectCode(String companyCode) {
        CompanyPO companyPO = companyMapper.selectOne(new LambdaQueryWrapper<CompanyPO>()
                .eq(CompanyPO::getCompanyCode, companyCode));
        CompanyDTO companyDTO = new CompanyDTO();
        BeanUtils.copyProperties(companyPO,companyDTO );
        return companyDTO;
    }
//查询公司名称
    @Override
    public CompanyDTO  selectName(String companyName ,String companyCode) {
        CompanyPO companyPO = companyMapper.selectOne(new LambdaQueryWrapper<CompanyPO>()
                .eq(CompanyPO::getCompanyShortNameCn ,companyName)
                .eq(CompanyPO::getCompanyCode,companyCode));
        CompanyDTO companyDTO = new CompanyDTO();
        BeanUtils.copyProperties(companyPO,companyDTO );
       return companyDTO;
    }

    public Integer selectDealerType(String dealerType) {
        if (!StringUtils.isNullOrEmpty(dealerType)) {
            if ("01".equals(dealerType)) {
                return CommonConstants.DEALER_SERVICE_CODE;
            } else if ("02".equals(dealerType)) {
                return CommonConstants.MAJOR_CLIENTS_CODE;
            }
        }
        return null;
    }


}
